package com.forcht.server.handler.impl;

import com.forcht.common.domain.*;
import com.forcht.common.enumeration.ResponseCode;
import com.forcht.common.enumeration.ResponseType;
import com.forcht.common.util.ProtostuffUtil;
import com.forcht.server.dao.ChatOneDao;
import com.forcht.server.handler.MessageHandler;
import com.forcht.server.handler.UserHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Date;

/**
 * Created by forcht on 2018/4/14.
 */
@Component("messageHandler.chat_one")
public class ChatOneMessageHandler extends MessageHandler {

    @Autowired
    private UserHandler userHandler;
    @Autowired
    private ChatOneDao chatOneDao;
    @Override
    public void handle(Message message, SelectionKey key) {
        System.out.println("服务器接收到客户端发送的数据：" + message);
        //解析请求
        MessageHeader header = message.getHeader();
        String receiver = header.getReceiver();
        String sender = header.getSender();
        SocketChannel receiverSocketChannel = userHandler.getUserSocketChannel(receiver);
        //如果接收方没有在线
        //先把消息保存在数据库
        if(receiverSocketChannel==null){
            ChatOne chatOne = ChatOne.builder().sender(sender).
                    receiver(receiver).content(new String(message.getBody()))
                    .timestamp(header.getTimestamp()).build();
            chatOneDao.insertChatContent(chatOne);
        }else{
            //包装转发数据
            Response receiverResponse = Response.builder().header(
                    ResponseHeader.builder()
                            .sender(sender)
                            .responseType(ResponseType.MESSAGE)
                            .responseCode(ResponseCode.CHAT_ONE)
                            .timestamp(new Date()).build()).body(message.getBody()).build();
            try {
                //转发数据
                receiverSocketChannel.write(ByteBuffer.wrap(ProtostuffUtil.serialize(receiverResponse)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
